home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / logging / __init__.pyc (.txt)
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  43.5 KB  |  1,413 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. """
  5. Logging package for Python. Based on PEP 282 and comments thereto in
  6. comp.lang.python, and influenced by Apache's log4j system.
  7.  
  8. Should work under Python versions >= 1.5.2, except that source line
  9. information is not available unless 'sys._getframe()' is.
  10.  
  11. Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
  12.  
  13. To use, simply 'import logging' and log away!
  14. """
  15. import sys
  16. import os
  17. import types
  18. import time
  19. import string
  20. import cStringIO
  21. import traceback
  22.  
  23. try:
  24.     import codecs
  25. except ImportError:
  26.     codecs = None
  27.  
  28.  
  29. try:
  30.     import thread
  31.     import threading
  32. except ImportError:
  33.     thread = None
  34.  
  35. __author__ = 'Vinay Sajip <vinay_sajip@red-dove.com>'
  36. __status__ = 'production'
  37. __version__ = '0.4.9.9'
  38. __date__ = '06 February 2006'
  39. if hasattr(sys, 'frozen'):
  40.     _srcfile = 'logging%s__init__%s' % (os.sep, __file__[-4:])
  41. elif string.lower(__file__[-4:]) in ('.pyc', '.pyo'):
  42.     _srcfile = __file__[:-4] + '.py'
  43. else:
  44.     _srcfile = __file__
  45. _srcfile = os.path.normcase(_srcfile)
  46.  
  47. def currentframe():
  48.     """Return the frame object for the caller's stack frame."""
  49.     
  50.     try:
  51.         raise Exception
  52.     except:
  53.         return sys.exc_traceback.tb_frame.f_back
  54.  
  55.  
  56. if hasattr(sys, '_getframe'):
  57.     currentframe = sys._getframe
  58.  
  59. _startTime = time.time()
  60. raiseExceptions = 1
  61. logThreads = 1
  62. logProcesses = 1
  63. CRITICAL = 50
  64. FATAL = CRITICAL
  65. ERROR = 40
  66. WARNING = 30
  67. WARN = WARNING
  68. INFO = 20
  69. DEBUG = 10
  70. NOTSET = 0
  71. _levelNames = {
  72.     CRITICAL: 'CRITICAL',
  73.     ERROR: 'ERROR',
  74.     WARNING: 'WARNING',
  75.     INFO: 'INFO',
  76.     DEBUG: 'DEBUG',
  77.     NOTSET: 'NOTSET',
  78.     'CRITICAL': CRITICAL,
  79.     'ERROR': ERROR,
  80.     'WARN': WARNING,
  81.     'WARNING': WARNING,
  82.     'INFO': INFO,
  83.     'DEBUG': DEBUG,
  84.     'NOTSET': NOTSET }
  85.  
  86. def getLevelName(level):
  87.     '''
  88.     Return the textual representation of logging level \'level\'.
  89.  
  90.     If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
  91.     INFO, DEBUG) then you get the corresponding string. If you have
  92.     associated levels with names using addLevelName then the name you have
  93.     associated with \'level\' is returned.
  94.  
  95.     If a numeric value corresponding to one of the defined levels is passed
  96.     in, the corresponding string representation is returned.
  97.  
  98.     Otherwise, the string "Level %s" % level is returned.
  99.     '''
  100.     return _levelNames.get(level, 'Level %s' % level)
  101.  
  102.  
  103. def addLevelName(level, levelName):
  104.     """
  105.     Associate 'levelName' with 'level'.
  106.  
  107.     This is used when converting levels to text during message formatting.
  108.     """
  109.     _acquireLock()
  110.     
  111.     try:
  112.         _levelNames[level] = levelName
  113.         _levelNames[levelName] = level
  114.     finally:
  115.         _releaseLock()
  116.  
  117.  
  118. _lock = None
  119.  
  120. def _acquireLock():
  121.     '''
  122.     Acquire the module-level lock for serializing access to shared data.
  123.  
  124.     This should be released with _releaseLock().
  125.     '''
  126.     global _lock
  127.     if not _lock and thread:
  128.         _lock = threading.RLock()
  129.     
  130.     if _lock:
  131.         _lock.acquire()
  132.     
  133.  
  134.  
  135. def _releaseLock():
  136.     '''
  137.     Release the module-level lock acquired by calling _acquireLock().
  138.     '''
  139.     if _lock:
  140.         _lock.release()
  141.     
  142.  
  143.  
  144. class LogRecord:
  145.     '''
  146.     A LogRecord instance represents an event being logged.
  147.  
  148.     LogRecord instances are created every time something is logged. They
  149.     contain all the information pertinent to the event being logged. The
  150.     main information passed in is in msg and args, which are combined
  151.     using str(msg) % args to create the message field of the record. The
  152.     record also includes information such as when the record was created,
  153.     the source line where the logging call was made, and any exception
  154.     information to be logged.
  155.     '''
  156.     
  157.     def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func):
  158.         '''
  159.         Initialize a logging record with interesting information.
  160.         '''
  161.         ct = time.time()
  162.         self.name = name
  163.         self.msg = msg
  164.         if args and len(args) == 1 and args[0] and type(args[0]) == types.DictType:
  165.             args = args[0]
  166.         
  167.         self.args = args
  168.         self.levelname = getLevelName(level)
  169.         self.levelno = level
  170.         self.pathname = pathname
  171.         
  172.         try:
  173.             self.filename = os.path.basename(pathname)
  174.             self.module = os.path.splitext(self.filename)[0]
  175.         except:
  176.             self.filename = pathname
  177.             self.module = 'Unknown module'
  178.  
  179.         self.exc_info = exc_info
  180.         self.exc_text = None
  181.         self.lineno = lineno
  182.         self.funcName = func
  183.         self.created = ct
  184.         self.msecs = (ct - long(ct)) * 1000
  185.         self.relativeCreated = (self.created - _startTime) * 1000
  186.         if logThreads and thread:
  187.             self.thread = thread.get_ident()
  188.             self.threadName = threading.currentThread().getName()
  189.         else:
  190.             self.thread = None
  191.             self.threadName = None
  192.         if logProcesses and hasattr(os, 'getpid'):
  193.             self.process = os.getpid()
  194.         else:
  195.             self.process = None
  196.  
  197.     
  198.     def __str__(self):
  199.         return '<LogRecord: %s, %s, %s, %s, "%s">' % (self.name, self.levelno, self.pathname, self.lineno, self.msg)
  200.  
  201.     
  202.     def getMessage(self):
  203.         '''
  204.         Return the message for this LogRecord.
  205.  
  206.         Return the message for this LogRecord after merging any user-supplied
  207.         arguments with the message.
  208.         '''
  209.         if not hasattr(types, 'UnicodeType'):
  210.             msg = str(self.msg)
  211.         else:
  212.             msg = self.msg
  213.             if type(msg) not in (types.UnicodeType, types.StringType):
  214.                 
  215.                 try:
  216.                     msg = str(self.msg)
  217.                 except UnicodeError:
  218.                     msg = self.msg
  219.                 except:
  220.                     None<EXCEPTION MATCH>UnicodeError
  221.                 
  222.  
  223.             None<EXCEPTION MATCH>UnicodeError
  224.         if self.args:
  225.             msg = msg % self.args
  226.         
  227.         return msg
  228.  
  229.  
  230.  
  231. def makeLogRecord(dict):
  232.     '''
  233.     Make a LogRecord whose attributes are defined by the specified dictionary,
  234.     This function is useful for converting a logging event received over
  235.     a socket connection (which is sent as a dictionary) into a LogRecord
  236.     instance.
  237.     '''
  238.     rv = LogRecord(None, None, '', 0, '', (), None, None)
  239.     rv.__dict__.update(dict)
  240.     return rv
  241.  
  242.  
  243. class Formatter:
  244.     '''
  245.     Formatter instances are used to convert a LogRecord to text.
  246.  
  247.     Formatters need to know how a LogRecord is constructed. They are
  248.     responsible for converting a LogRecord to (usually) a string which can
  249.     be interpreted by either a human or an external system. The base Formatter
  250.     allows a formatting string to be specified. If none is supplied, the
  251.     default value of "%s(message)\\n" is used.
  252.  
  253.     The Formatter can be initialized with a format string which makes use of
  254.     knowledge of the LogRecord attributes - e.g. the default value mentioned
  255.     above makes use of the fact that the user\'s message and arguments are pre-
  256.     formatted into a LogRecord\'s message attribute. Currently, the useful
  257.     attributes in a LogRecord are described by:
  258.  
  259.     %(name)s            Name of the logger (logging channel)
  260.     %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
  261.                         WARNING, ERROR, CRITICAL)
  262.     %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
  263.                         "WARNING", "ERROR", "CRITICAL")
  264.     %(pathname)s        Full pathname of the source file where the logging
  265.                         call was issued (if available)
  266.     %(filename)s        Filename portion of pathname
  267.     %(module)s          Module (name portion of filename)
  268.     %(lineno)d          Source line number where the logging call was issued
  269.                         (if available)
  270.     %(funcName)s        Function name
  271.     %(created)f         Time when the LogRecord was created (time.time()
  272.                         return value)
  273.     %(asctime)s         Textual time when the LogRecord was created
  274.     %(msecs)d           Millisecond portion of the creation time
  275.     %(relativeCreated)d Time in milliseconds when the LogRecord was created,
  276.                         relative to the time the logging module was loaded
  277.                         (typically at application startup time)
  278.     %(thread)d          Thread ID (if available)
  279.     %(threadName)s      Thread name (if available)
  280.     %(process)d         Process ID (if available)
  281.     %(message)s         The result of record.getMessage(), computed just as
  282.                         the record is emitted
  283.     '''
  284.     converter = time.localtime
  285.     
  286.     def __init__(self, fmt = None, datefmt = None):
  287.         '''
  288.         Initialize the formatter with specified format strings.
  289.  
  290.         Initialize the formatter either with the specified format string, or a
  291.         default as described above. Allow for specialized date formatting with
  292.         the optional datefmt argument (if omitted, you get the ISO8601 format).
  293.         '''
  294.         if fmt:
  295.             self._fmt = fmt
  296.         else:
  297.             self._fmt = '%(message)s'
  298.         self.datefmt = datefmt
  299.  
  300.     
  301.     def formatTime(self, record, datefmt = None):
  302.         """
  303.         Return the creation time of the specified LogRecord as formatted text.
  304.  
  305.         This method should be called from format() by a formatter which
  306.         wants to make use of a formatted time. This method can be overridden
  307.         in formatters to provide for any specific requirement, but the
  308.         basic behaviour is as follows: if datefmt (a string) is specified,
  309.         it is used with time.strftime() to format the creation time of the
  310.         record. Otherwise, the ISO8601 format is used. The resulting
  311.         string is returned. This function uses a user-configurable function
  312.         to convert the creation time to a tuple. By default, time.localtime()
  313.         is used; to change this for a particular formatter instance, set the
  314.         'converter' attribute to a function with the same signature as
  315.         time.localtime() or time.gmtime(). To change it for all formatters,
  316.         for example if you want all logging times to be shown in GMT,
  317.         set the 'converter' attribute in the Formatter class.
  318.         """
  319.         ct = self.converter(record.created)
  320.         if datefmt:
  321.             s = time.strftime(datefmt, ct)
  322.         else:
  323.             t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
  324.             s = '%s,%03d' % (t, record.msecs)
  325.         return s
  326.  
  327.     
  328.     def formatException(self, ei):
  329.         '''
  330.         Format and return the specified exception information as a string.
  331.  
  332.         This default implementation just uses
  333.         traceback.print_exception()
  334.         '''
  335.         sio = cStringIO.StringIO()
  336.         traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
  337.         s = sio.getvalue()
  338.         sio.close()
  339.         if s[-1] == '\n':
  340.             s = s[:-1]
  341.         
  342.         return s
  343.  
  344.     
  345.     def format(self, record):
  346.         '''
  347.         Format the specified record as text.
  348.  
  349.         The record\'s attribute dictionary is used as the operand to a
  350.         string formatting operation which yields the returned string.
  351.         Before formatting the dictionary, a couple of preparatory steps
  352.         are carried out. The message attribute of the record is computed
  353.         using LogRecord.getMessage(). If the formatting string contains
  354.         "%(asctime)", formatTime() is called to format the event time.
  355.         If there is exception information, it is formatted using
  356.         formatException() and appended to the message.
  357.         '''
  358.         record.message = record.getMessage()
  359.         if string.find(self._fmt, '%(asctime)') >= 0:
  360.             record.asctime = self.formatTime(record, self.datefmt)
  361.         
  362.         s = self._fmt % record.__dict__
  363.         if record.exc_info:
  364.             if not record.exc_text:
  365.                 record.exc_text = self.formatException(record.exc_info)
  366.             
  367.         
  368.         if record.exc_text:
  369.             if s[-1] != '\n':
  370.                 s = s + '\n'
  371.             
  372.             s = s + record.exc_text
  373.         
  374.         return s
  375.  
  376.  
  377. _defaultFormatter = Formatter()
  378.  
  379. class BufferingFormatter:
  380.     '''
  381.     A formatter suitable for formatting a number of records.
  382.     '''
  383.     
  384.     def __init__(self, linefmt = None):
  385.         '''
  386.         Optionally specify a formatter which will be used to format each
  387.         individual record.
  388.         '''
  389.         if linefmt:
  390.             self.linefmt = linefmt
  391.         else:
  392.             self.linefmt = _defaultFormatter
  393.  
  394.     
  395.     def formatHeader(self, records):
  396.         '''
  397.         Return the header string for the specified records.
  398.         '''
  399.         return ''
  400.  
  401.     
  402.     def formatFooter(self, records):
  403.         '''
  404.         Return the footer string for the specified records.
  405.         '''
  406.         return ''
  407.  
  408.     
  409.     def format(self, records):
  410.         '''
  411.         Format the specified records and return the result as a string.
  412.         '''
  413.         rv = ''
  414.         if len(records) > 0:
  415.             rv = rv + self.formatHeader(records)
  416.             for record in records:
  417.                 rv = rv + self.linefmt.format(record)
  418.             
  419.             rv = rv + self.formatFooter(records)
  420.         
  421.         return rv
  422.  
  423.  
  424.  
  425. class Filter:
  426.     '''
  427.     Filter instances are used to perform arbitrary filtering of LogRecords.
  428.  
  429.     Loggers and Handlers can optionally use Filter instances to filter
  430.     records as desired. The base filter class only allows events which are
  431.     below a certain point in the logger hierarchy. For example, a filter
  432.     initialized with "A.B" will allow events logged by loggers "A.B",
  433.     "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
  434.     initialized with the empty string, all events are passed.
  435.     '''
  436.     
  437.     def __init__(self, name = ''):
  438.         '''
  439.         Initialize a filter.
  440.  
  441.         Initialize with the name of the logger which, together with its
  442.         children, will have its events allowed through the filter. If no
  443.         name is specified, allow every event.
  444.         '''
  445.         self.name = name
  446.         self.nlen = len(name)
  447.  
  448.     
  449.     def filter(self, record):
  450.         '''
  451.         Determine if the specified record is to be logged.
  452.  
  453.         Is the specified record to be logged? Returns 0 for no, nonzero for
  454.         yes. If deemed appropriate, the record may be modified in-place.
  455.         '''
  456.         if self.nlen == 0:
  457.             return 1
  458.         elif self.name == record.name:
  459.             return 1
  460.         elif string.find(record.name, self.name, 0, self.nlen) != 0:
  461.             return 0
  462.         
  463.         return record.name[self.nlen] == '.'
  464.  
  465.  
  466.  
  467. class Filterer:
  468.     '''
  469.     A base class for loggers and handlers which allows them to share
  470.     common code.
  471.     '''
  472.     
  473.     def __init__(self):
  474.         '''
  475.         Initialize the list of filters to be an empty list.
  476.         '''
  477.         self.filters = []
  478.  
  479.     
  480.     def addFilter(self, filter):
  481.         '''
  482.         Add the specified filter to this handler.
  483.         '''
  484.         if filter not in self.filters:
  485.             self.filters.append(filter)
  486.         
  487.  
  488.     
  489.     def removeFilter(self, filter):
  490.         '''
  491.         Remove the specified filter from this handler.
  492.         '''
  493.         if filter in self.filters:
  494.             self.filters.remove(filter)
  495.         
  496.  
  497.     
  498.     def filter(self, record):
  499.         '''
  500.         Determine if a record is loggable by consulting all the filters.
  501.  
  502.         The default is to allow the record to be logged; any filter can veto
  503.         this and the record is then dropped. Returns a zero value if a record
  504.         is to be dropped, else non-zero.
  505.         '''
  506.         rv = 1
  507.         for f in self.filters:
  508.             if not f.filter(record):
  509.                 rv = 0
  510.                 break
  511.                 continue
  512.         
  513.         return rv
  514.  
  515.  
  516. _handlers = { }
  517. _handlerList = []
  518.  
  519. class Handler(Filterer):
  520.     """
  521.     Handler instances dispatch logging events to specific destinations.
  522.  
  523.     The base handler class. Acts as a placeholder which defines the Handler
  524.     interface. Handlers can optionally use Formatter instances to format
  525.     records as desired. By default, no formatter is specified; in this case,
  526.     the 'raw' message as determined by record.message is logged.
  527.     """
  528.     
  529.     def __init__(self, level = NOTSET):
  530.         '''
  531.         Initializes the instance - basically setting the formatter to None
  532.         and the filter list to empty.
  533.         '''
  534.         Filterer.__init__(self)
  535.         self.level = level
  536.         self.formatter = None
  537.         _acquireLock()
  538.         
  539.         try:
  540.             _handlers[self] = 1
  541.             _handlerList.insert(0, self)
  542.         finally:
  543.             _releaseLock()
  544.  
  545.         self.createLock()
  546.  
  547.     
  548.     def createLock(self):
  549.         '''
  550.         Acquire a thread lock for serializing access to the underlying I/O.
  551.         '''
  552.         if thread:
  553.             self.lock = threading.RLock()
  554.         else:
  555.             self.lock = None
  556.  
  557.     
  558.     def acquire(self):
  559.         '''
  560.         Acquire the I/O thread lock.
  561.         '''
  562.         if self.lock:
  563.             self.lock.acquire()
  564.         
  565.  
  566.     
  567.     def release(self):
  568.         '''
  569.         Release the I/O thread lock.
  570.         '''
  571.         if self.lock:
  572.             self.lock.release()
  573.         
  574.  
  575.     
  576.     def setLevel(self, level):
  577.         '''
  578.         Set the logging level of this handler.
  579.         '''
  580.         self.level = level
  581.  
  582.     
  583.     def format(self, record):
  584.         '''
  585.         Format the specified record.
  586.  
  587.         If a formatter is set, use it. Otherwise, use the default formatter
  588.         for the module.
  589.         '''
  590.         if self.formatter:
  591.             fmt = self.formatter
  592.         else:
  593.             fmt = _defaultFormatter
  594.         return fmt.format(record)
  595.  
  596.     
  597.     def emit(self, record):
  598.         '''
  599.         Do whatever it takes to actually log the specified logging record.
  600.  
  601.         This version is intended to be implemented by subclasses and so
  602.         raises a NotImplementedError.
  603.         '''
  604.         raise NotImplementedError, 'emit must be implemented by Handler subclasses'
  605.  
  606.     
  607.     def handle(self, record):
  608.         '''
  609.         Conditionally emit the specified logging record.
  610.  
  611.         Emission depends on filters which may have been added to the handler.
  612.         Wrap the actual emission of the record with acquisition/release of
  613.         the I/O thread lock. Returns whether the filter passed the record for
  614.         emission.
  615.         '''
  616.         rv = self.filter(record)
  617.         if rv:
  618.             self.acquire()
  619.             
  620.             try:
  621.                 self.emit(record)
  622.             finally:
  623.                 self.release()
  624.  
  625.         
  626.         return rv
  627.  
  628.     
  629.     def setFormatter(self, fmt):
  630.         '''
  631.         Set the formatter for this handler.
  632.         '''
  633.         self.formatter = fmt
  634.  
  635.     
  636.     def flush(self):
  637.         '''
  638.         Ensure all logging output has been flushed.
  639.  
  640.         This version does nothing and is intended to be implemented by
  641.         subclasses.
  642.         '''
  643.         pass
  644.  
  645.     
  646.     def close(self):
  647.         '''
  648.         Tidy up any resources used by the handler.
  649.  
  650.         This version does removes the handler from an internal list
  651.         of handlers which is closed when shutdown() is called. Subclasses
  652.         should ensure that this gets called from overridden close()
  653.         methods.
  654.         '''
  655.         _acquireLock()
  656.         
  657.         try:
  658.             del _handlers[self]
  659.             _handlerList.remove(self)
  660.         finally:
  661.             _releaseLock()
  662.  
  663.  
  664.     
  665.     def handleError(self, record):
  666.         '''
  667.         Handle errors which occur during an emit() call.
  668.  
  669.         This method should be called from handlers when an exception is
  670.         encountered during an emit() call. If raiseExceptions is false,
  671.         exceptions get silently ignored. This is what is mostly wanted
  672.         for a logging system - most users will not care about errors in
  673.         the logging system, they are more interested in application errors.
  674.         You could, however, replace this with a custom handler if you wish.
  675.         The record which was being processed is passed in to this method.
  676.         '''
  677.         if raiseExceptions:
  678.             ei = sys.exc_info()
  679.             traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
  680.             del ei
  681.         
  682.  
  683.  
  684.  
  685. class StreamHandler(Handler):
  686.     '''
  687.     A handler class which writes logging records, appropriately formatted,
  688.     to a stream. Note that this class does not close the stream, as
  689.     sys.stdout or sys.stderr may be used.
  690.     '''
  691.     
  692.     def __init__(self, strm = None):
  693.         '''
  694.         Initialize the handler.
  695.  
  696.         If strm is not specified, sys.stderr is used.
  697.         '''
  698.         Handler.__init__(self)
  699.         if strm is None:
  700.             strm = sys.stderr
  701.         
  702.         self.stream = strm
  703.         self.formatter = None
  704.  
  705.     
  706.     def flush(self):
  707.         '''
  708.         Flushes the stream.
  709.         '''
  710.         self.stream.flush()
  711.  
  712.     
  713.     def emit(self, record):
  714.         '''
  715.         Emit a record.
  716.  
  717.         If a formatter is specified, it is used to format the record.
  718.         The record is then written to the stream with a trailing newline
  719.         [N.B. this may be removed depending on feedback]. If exception
  720.         information is present, it is formatted using
  721.         traceback.print_exception and appended to the stream.
  722.         '''
  723.         
  724.         try:
  725.             msg = self.format(record)
  726.             fs = '%s\n'
  727.             if not hasattr(types, 'UnicodeType'):
  728.                 self.stream.write(fs % msg)
  729.             else:
  730.                 
  731.                 try:
  732.                     self.stream.write(fs % msg)
  733.                 except UnicodeError:
  734.                     self.stream.write(fs % msg.encode('UTF-8'))
  735.  
  736.             self.flush()
  737.         except (KeyboardInterrupt, SystemExit):
  738.             raise 
  739.         except:
  740.             self.handleError(record)
  741.  
  742.  
  743.  
  744.  
  745. class FileHandler(StreamHandler):
  746.     '''
  747.     A handler class which writes formatted logging records to disk files.
  748.     '''
  749.     
  750.     def __init__(self, filename, mode = 'a', encoding = None):
  751.         '''
  752.         Open the specified file and use it as the stream for logging.
  753.         '''
  754.         if codecs is None:
  755.             encoding = None
  756.         
  757.         if encoding is None:
  758.             stream = open(filename, mode)
  759.         else:
  760.             stream = codecs.open(filename, mode, encoding)
  761.         StreamHandler.__init__(self, stream)
  762.         self.baseFilename = os.path.abspath(filename)
  763.         self.mode = mode
  764.  
  765.     
  766.     def close(self):
  767.         '''
  768.         Closes the stream.
  769.         '''
  770.         self.flush()
  771.         self.stream.close()
  772.         StreamHandler.close(self)
  773.  
  774.  
  775.  
  776. class PlaceHolder:
  777.     '''
  778.     PlaceHolder instances are used in the Manager logger hierarchy to take
  779.     the place of nodes for which no loggers have been defined. This class is
  780.     intended for internal use only and not as part of the public API.
  781.     '''
  782.     
  783.     def __init__(self, alogger):
  784.         '''
  785.         Initialize with the specified logger being a child of this placeholder.
  786.         '''
  787.         self.loggerMap = {
  788.             alogger: None }
  789.  
  790.     
  791.     def append(self, alogger):
  792.         '''
  793.         Add the specified logger as a child of this placeholder.
  794.         '''
  795.         if not self.loggerMap.has_key(alogger):
  796.             self.loggerMap[alogger] = None
  797.         
  798.  
  799.  
  800. _loggerClass = None
  801.  
  802. def setLoggerClass(klass):
  803.     '''
  804.     Set the class to be used when instantiating a logger. The class should
  805.     define __init__() such that only a name argument is required, and the
  806.     __init__() should call Logger.__init__()
  807.     '''
  808.     global _loggerClass
  809.     if klass != Logger:
  810.         if not issubclass(klass, Logger):
  811.             raise TypeError, 'logger not derived from logging.Logger: ' + klass.__name__
  812.         
  813.     
  814.     _loggerClass = klass
  815.  
  816.  
  817. def getLoggerClass():
  818.     '''
  819.     Return the class to be used when instantiating a logger.
  820.     '''
  821.     return _loggerClass
  822.  
  823.  
  824. class Manager:
  825.     '''
  826.     There is [under normal circumstances] just one Manager instance, which
  827.     holds the hierarchy of loggers.
  828.     '''
  829.     
  830.     def __init__(self, rootnode):
  831.         '''
  832.         Initialize the manager with the root node of the logger hierarchy.
  833.         '''
  834.         self.root = rootnode
  835.         self.disable = 0
  836.         self.emittedNoHandlerWarning = 0
  837.         self.loggerDict = { }
  838.  
  839.     
  840.     def getLogger(self, name):
  841.         '''
  842.         Get a logger with the specified name (channel name), creating it
  843.         if it doesn\'t yet exist. This name is a dot-separated hierarchical
  844.         name, such as "a", "a.b", "a.b.c" or similar.
  845.  
  846.         If a PlaceHolder existed for the specified name [i.e. the logger
  847.         didn\'t exist but a child of it did], replace it with the created
  848.         logger and fix up the parent/child references which pointed to the
  849.         placeholder to now point to the logger.
  850.         '''
  851.         rv = None
  852.         _acquireLock()
  853.         
  854.         try:
  855.             if self.loggerDict.has_key(name):
  856.                 rv = self.loggerDict[name]
  857.                 if isinstance(rv, PlaceHolder):
  858.                     ph = rv
  859.                     rv = _loggerClass(name)
  860.                     rv.manager = self
  861.                     self.loggerDict[name] = rv
  862.                     self._fixupChildren(ph, rv)
  863.                     self._fixupParents(rv)
  864.                 
  865.             else:
  866.                 rv = _loggerClass(name)
  867.                 rv.manager = self
  868.                 self.loggerDict[name] = rv
  869.                 self._fixupParents(rv)
  870.         finally:
  871.             _releaseLock()
  872.  
  873.         return rv
  874.  
  875.     
  876.     def _fixupParents(self, alogger):
  877.         '''
  878.         Ensure that there are either loggers or placeholders all the way
  879.         from the specified logger to the root of the logger hierarchy.
  880.         '''
  881.         name = alogger.name
  882.         i = string.rfind(name, '.')
  883.         rv = None
  884.         while i > 0 and not rv:
  885.             substr = name[:i]
  886.             if not self.loggerDict.has_key(substr):
  887.                 self.loggerDict[substr] = PlaceHolder(alogger)
  888.             else:
  889.                 obj = self.loggerDict[substr]
  890.                 if isinstance(obj, Logger):
  891.                     rv = obj
  892.                 elif not isinstance(obj, PlaceHolder):
  893.                     raise AssertionError
  894.                 obj.append(alogger)
  895.             i = string.rfind(name, '.', 0, i - 1)
  896.         if not rv:
  897.             rv = self.root
  898.         
  899.         alogger.parent = rv
  900.  
  901.     
  902.     def _fixupChildren(self, ph, alogger):
  903.         '''
  904.         Ensure that children of the placeholder ph are connected to the
  905.         specified logger.
  906.         '''
  907.         for c in ph.loggerMap.keys():
  908.             if string.find(c.parent.name, alogger.name) != 0:
  909.                 alogger.parent = c.parent
  910.                 c.parent = alogger
  911.                 continue
  912.         
  913.  
  914.  
  915.  
  916. class Logger(Filterer):
  917.     '''
  918.     Instances of the Logger class represent a single logging channel. A
  919.     "logging channel" indicates an area of an application. Exactly how an
  920.     "area" is defined is up to the application developer. Since an
  921.     application can have any number of areas, logging channels are identified
  922.     by a unique string. Application areas can be nested (e.g. an area
  923.     of "input processing" might include sub-areas "read CSV files", "read
  924.     XLS files" and "read Gnumeric files"). To cater for this natural nesting,
  925.     channel names are organized into a namespace hierarchy where levels are
  926.     separated by periods, much like the Java or Python package namespace. So
  927.     in the instance given above, channel names might be "input" for the upper
  928.     level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
  929.     There is no arbitrary limit to the depth of nesting.
  930.     '''
  931.     
  932.     def __init__(self, name, level = NOTSET):
  933.         '''
  934.         Initialize the logger with a name and an optional level.
  935.         '''
  936.         Filterer.__init__(self)
  937.         self.name = name
  938.         self.level = level
  939.         self.parent = None
  940.         self.propagate = 1
  941.         self.handlers = []
  942.         self.disabled = 0
  943.  
  944.     
  945.     def setLevel(self, level):
  946.         '''
  947.         Set the logging level of this logger.
  948.         '''
  949.         self.level = level
  950.  
  951.     
  952.     def debug(self, msg, *args, **kwargs):
  953.         '''
  954.         Log \'msg % args\' with severity \'DEBUG\'.
  955.  
  956.         To pass exception information, use the keyword argument exc_info with
  957.         a true value, e.g.
  958.  
  959.         logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
  960.         '''
  961.         if self.manager.disable >= DEBUG:
  962.             return None
  963.         
  964.         if DEBUG >= self.getEffectiveLevel():
  965.             apply(self._log, (DEBUG, msg, args), kwargs)
  966.         
  967.  
  968.     
  969.     def info(self, msg, *args, **kwargs):
  970.         '''
  971.         Log \'msg % args\' with severity \'INFO\'.
  972.  
  973.         To pass exception information, use the keyword argument exc_info with
  974.         a true value, e.g.
  975.  
  976.         logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
  977.         '''
  978.         if self.manager.disable >= INFO:
  979.             return None
  980.         
  981.         if INFO >= self.getEffectiveLevel():
  982.             apply(self._log, (INFO, msg, args), kwargs)
  983.         
  984.  
  985.     
  986.     def warning(self, msg, *args, **kwargs):
  987.         '''
  988.         Log \'msg % args\' with severity \'WARNING\'.
  989.  
  990.         To pass exception information, use the keyword argument exc_info with
  991.         a true value, e.g.
  992.  
  993.         logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
  994.         '''
  995.         if self.manager.disable >= WARNING:
  996.             return None
  997.         
  998.         if self.isEnabledFor(WARNING):
  999.             apply(self._log, (WARNING, msg, args), kwargs)
  1000.         
  1001.  
  1002.     warn = warning
  1003.     
  1004.     def error(self, msg, *args, **kwargs):
  1005.         '''
  1006.         Log \'msg % args\' with severity \'ERROR\'.
  1007.  
  1008.         To pass exception information, use the keyword argument exc_info with
  1009.         a true value, e.g.
  1010.  
  1011.         logger.error("Houston, we have a %s", "major problem", exc_info=1)
  1012.         '''
  1013.         if self.manager.disable >= ERROR:
  1014.             return None
  1015.         
  1016.         if self.isEnabledFor(ERROR):
  1017.             apply(self._log, (ERROR, msg, args), kwargs)
  1018.         
  1019.  
  1020.     
  1021.     def exception(self, msg, *args):
  1022.         '''
  1023.         Convenience method for logging an ERROR with exception information.
  1024.         '''
  1025.         apply(self.error, (msg,) + args, {
  1026.             'exc_info': 1 })
  1027.  
  1028.     
  1029.     def critical(self, msg, *args, **kwargs):
  1030.         '''
  1031.         Log \'msg % args\' with severity \'CRITICAL\'.
  1032.  
  1033.         To pass exception information, use the keyword argument exc_info with
  1034.         a true value, e.g.
  1035.  
  1036.         logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
  1037.         '''
  1038.         if self.manager.disable >= CRITICAL:
  1039.             return None
  1040.         
  1041.         if CRITICAL >= self.getEffectiveLevel():
  1042.             apply(self._log, (CRITICAL, msg, args), kwargs)
  1043.         
  1044.  
  1045.     fatal = critical
  1046.     
  1047.     def log(self, level, msg, *args, **kwargs):
  1048.         '''
  1049.         Log \'msg % args\' with the integer severity \'level\'.
  1050.  
  1051.         To pass exception information, use the keyword argument exc_info with
  1052.         a true value, e.g.
  1053.  
  1054.         logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
  1055.         '''
  1056.         if type(level) != types.IntType:
  1057.             if raiseExceptions:
  1058.                 raise TypeError, 'level must be an integer'
  1059.             else:
  1060.                 return None
  1061.         
  1062.         if self.manager.disable >= level:
  1063.             return None
  1064.         
  1065.         if self.isEnabledFor(level):
  1066.             apply(self._log, (level, msg, args), kwargs)
  1067.         
  1068.  
  1069.     
  1070.     def findCaller(self):
  1071.         '''
  1072.         Find the stack frame of the caller so that we can note the source
  1073.         file name, line number and function name.
  1074.         '''
  1075.         f = currentframe().f_back
  1076.         rv = ('(unknown file)', 0, '(unknown function)')
  1077.         while hasattr(f, 'f_code'):
  1078.             co = f.f_code
  1079.             filename = os.path.normcase(co.co_filename)
  1080.             if filename == _srcfile:
  1081.                 f = f.f_back
  1082.                 continue
  1083.             
  1084.             rv = (filename, f.f_lineno, co.co_name)
  1085.             break
  1086.         return rv
  1087.  
  1088.     
  1089.     def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func = None, extra = None):
  1090.         '''
  1091.         A factory method which can be overridden in subclasses to create
  1092.         specialized LogRecords.
  1093.         '''
  1094.         rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
  1095.         if extra:
  1096.             for key in extra:
  1097.                 if key in ('message', 'asctime') or key in rv.__dict__:
  1098.                     raise KeyError('Attempt to overwrite %r in LogRecord' % key)
  1099.                 
  1100.                 rv.__dict__[key] = extra[key]
  1101.             
  1102.         
  1103.         return rv
  1104.  
  1105.     
  1106.     def _log(self, level, msg, args, exc_info = None, extra = None):
  1107.         '''
  1108.         Low-level logging routine which creates a LogRecord and then calls
  1109.         all the handlers of this logger to handle the record.
  1110.         '''
  1111.         if _srcfile:
  1112.             (fn, lno, func) = self.findCaller()
  1113.         else:
  1114.             (fn, lno, func) = ('(unknown file)', 0, '(unknown function)')
  1115.         if exc_info:
  1116.             if type(exc_info) != types.TupleType:
  1117.                 exc_info = sys.exc_info()
  1118.             
  1119.         
  1120.         record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
  1121.         self.handle(record)
  1122.  
  1123.     
  1124.     def handle(self, record):
  1125.         '''
  1126.         Call the handlers for the specified record.
  1127.  
  1128.         This method is used for unpickled records received from a socket, as
  1129.         well as those created locally. Logger-level filtering is applied.
  1130.         '''
  1131.         if not (self.disabled) and self.filter(record):
  1132.             self.callHandlers(record)
  1133.         
  1134.  
  1135.     
  1136.     def addHandler(self, hdlr):
  1137.         '''
  1138.         Add the specified handler to this logger.
  1139.         '''
  1140.         if hdlr not in self.handlers:
  1141.             self.handlers.append(hdlr)
  1142.         
  1143.  
  1144.     
  1145.     def removeHandler(self, hdlr):
  1146.         '''
  1147.         Remove the specified handler from this logger.
  1148.         '''
  1149.         if hdlr in self.handlers:
  1150.             hdlr.acquire()
  1151.             
  1152.             try:
  1153.                 self.handlers.remove(hdlr)
  1154.             finally:
  1155.                 hdlr.release()
  1156.  
  1157.         
  1158.  
  1159.     
  1160.     def callHandlers(self, record):
  1161.         '''
  1162.         Pass a record to all relevant handlers.
  1163.  
  1164.         Loop through all handlers for this logger and its parents in the
  1165.         logger hierarchy. If no handler was found, output a one-off error
  1166.         message to sys.stderr. Stop searching up the hierarchy whenever a
  1167.         logger with the "propagate" attribute set to zero is found - that
  1168.         will be the last logger whose handlers are called.
  1169.         '''
  1170.         c = self
  1171.         found = 0
  1172.         while c:
  1173.             for hdlr in c.handlers:
  1174.                 found = found + 1
  1175.                 if record.levelno >= hdlr.level:
  1176.                     hdlr.handle(record)
  1177.                     continue
  1178.             
  1179.             if not c.propagate:
  1180.                 c = None
  1181.                 continue
  1182.             c = c.parent
  1183.         if found == 0 and raiseExceptions and not (self.manager.emittedNoHandlerWarning):
  1184.             sys.stderr.write('No handlers could be found for logger "%s"\n' % self.name)
  1185.             self.manager.emittedNoHandlerWarning = 1
  1186.         
  1187.  
  1188.     
  1189.     def getEffectiveLevel(self):
  1190.         '''
  1191.         Get the effective level for this logger.
  1192.  
  1193.         Loop through this logger and its parents in the logger hierarchy,
  1194.         looking for a non-zero logging level. Return the first one found.
  1195.         '''
  1196.         logger = self
  1197.         while logger:
  1198.             if logger.level:
  1199.                 return logger.level
  1200.             
  1201.             logger = logger.parent
  1202.         return NOTSET
  1203.  
  1204.     
  1205.     def isEnabledFor(self, level):
  1206.         """
  1207.         Is this logger enabled for level 'level'?
  1208.         """
  1209.         if self.manager.disable >= level:
  1210.             return 0
  1211.         
  1212.         return level >= self.getEffectiveLevel()
  1213.  
  1214.  
  1215.  
  1216. class RootLogger(Logger):
  1217.     '''
  1218.     A root logger is not that different to any other logger, except that
  1219.     it must have a logging level and there is only one instance of it in
  1220.     the hierarchy.
  1221.     '''
  1222.     
  1223.     def __init__(self, level):
  1224.         '''
  1225.         Initialize the logger with the name "root".
  1226.         '''
  1227.         Logger.__init__(self, 'root', level)
  1228.  
  1229.  
  1230. _loggerClass = Logger
  1231. root = RootLogger(WARNING)
  1232. Logger.root = root
  1233. Logger.manager = Manager(Logger.root)
  1234. BASIC_FORMAT = '%(levelname)s:%(name)s:%(message)s'
  1235.  
  1236. def basicConfig(**kwargs):
  1237.     """
  1238.     Do basic configuration for the logging system.
  1239.  
  1240.     This function does nothing if the root logger already has handlers
  1241.     configured. It is a convenience method intended for use by simple scripts
  1242.     to do one-shot configuration of the logging package.
  1243.  
  1244.     The default behaviour is to create a StreamHandler which writes to
  1245.     sys.stderr, set a formatter using the BASIC_FORMAT format string, and
  1246.     add the handler to the root logger.
  1247.  
  1248.     A number of optional keyword arguments may be specified, which can alter
  1249.     the default behaviour.
  1250.  
  1251.     filename  Specifies that a FileHandler be created, using the specified
  1252.               filename, rather than a StreamHandler.
  1253.     filemode  Specifies the mode to open the file, if filename is specified
  1254.               (if filemode is unspecified, it defaults to 'a').
  1255.     format    Use the specified format string for the handler.
  1256.     datefmt   Use the specified date/time format.
  1257.     level     Set the root logger level to the specified level.
  1258.     stream    Use the specified stream to initialize the StreamHandler. Note
  1259.               that this argument is incompatible with 'filename' - if both
  1260.               are present, 'stream' is ignored.
  1261.  
  1262.     Note that you could specify a stream created using open(filename, mode)
  1263.     rather than passing the filename and mode in. However, it should be
  1264.     remembered that StreamHandler does not close its stream (since it may be
  1265.     using sys.stdout or sys.stderr), whereas FileHandler closes its stream
  1266.     when the handler is closed.
  1267.     """
  1268.     if len(root.handlers) == 0:
  1269.         filename = kwargs.get('filename')
  1270.         if filename:
  1271.             mode = kwargs.get('filemode', 'a')
  1272.             hdlr = FileHandler(filename, mode)
  1273.         else:
  1274.             stream = kwargs.get('stream')
  1275.             hdlr = StreamHandler(stream)
  1276.         fs = kwargs.get('format', BASIC_FORMAT)
  1277.         dfs = kwargs.get('datefmt', None)
  1278.         fmt = Formatter(fs, dfs)
  1279.         hdlr.setFormatter(fmt)
  1280.         root.addHandler(hdlr)
  1281.         level = kwargs.get('level')
  1282.         if level:
  1283.             root.setLevel(level)
  1284.         
  1285.     
  1286.  
  1287.  
  1288. def getLogger(name = None):
  1289.     '''
  1290.     Return a logger with the specified name, creating it if necessary.
  1291.  
  1292.     If no name is specified, return the root logger.
  1293.     '''
  1294.     if name:
  1295.         return Logger.manager.getLogger(name)
  1296.     else:
  1297.         return root
  1298.  
  1299.  
  1300. def critical(msg, *args, **kwargs):
  1301.     """
  1302.     Log a message with severity 'CRITICAL' on the root logger.
  1303.     """
  1304.     if len(root.handlers) == 0:
  1305.         basicConfig()
  1306.     
  1307.     apply(root.critical, (msg,) + args, kwargs)
  1308.  
  1309. fatal = critical
  1310.  
  1311. def error(msg, *args, **kwargs):
  1312.     """
  1313.     Log a message with severity 'ERROR' on the root logger.
  1314.     """
  1315.     if len(root.handlers) == 0:
  1316.         basicConfig()
  1317.     
  1318.     apply(root.error, (msg,) + args, kwargs)
  1319.  
  1320.  
  1321. def exception(msg, *args):
  1322.     """
  1323.     Log a message with severity 'ERROR' on the root logger,
  1324.     with exception information.
  1325.     """
  1326.     apply(error, (msg,) + args, {
  1327.         'exc_info': 1 })
  1328.  
  1329.  
  1330. def warning(msg, *args, **kwargs):
  1331.     """
  1332.     Log a message with severity 'WARNING' on the root logger.
  1333.     """
  1334.     if len(root.handlers) == 0:
  1335.         basicConfig()
  1336.     
  1337.     apply(root.warning, (msg,) + args, kwargs)
  1338.  
  1339. warn = warning
  1340.  
  1341. def info(msg, *args, **kwargs):
  1342.     """
  1343.     Log a message with severity 'INFO' on the root logger.
  1344.     """
  1345.     if len(root.handlers) == 0:
  1346.         basicConfig()
  1347.     
  1348.     apply(root.info, (msg,) + args, kwargs)
  1349.  
  1350.  
  1351. def debug(msg, *args, **kwargs):
  1352.     """
  1353.     Log a message with severity 'DEBUG' on the root logger.
  1354.     """
  1355.     if len(root.handlers) == 0:
  1356.         basicConfig()
  1357.     
  1358.     apply(root.debug, (msg,) + args, kwargs)
  1359.  
  1360.  
  1361. def log(level, msg, *args, **kwargs):
  1362.     """
  1363.     Log 'msg % args' with the integer severity 'level' on the root logger.
  1364.     """
  1365.     if len(root.handlers) == 0:
  1366.         basicConfig()
  1367.     
  1368.     apply(root.log, (level, msg) + args, kwargs)
  1369.  
  1370.  
  1371. def disable(level):
  1372.     """
  1373.     Disable all logging calls less severe than 'level'.
  1374.     """
  1375.     root.manager.disable = level
  1376.  
  1377.  
  1378. def shutdown(handlerList = _handlerList):
  1379.     '''
  1380.     Perform any cleanup actions in the logging system (e.g. flushing
  1381.     buffers).
  1382.  
  1383.     Should be called at application exit.
  1384.     '''
  1385.     for h in handlerList[:]:
  1386.         
  1387.         try:
  1388.             h.flush()
  1389.             h.close()
  1390.         continue
  1391.         if raiseExceptions:
  1392.             raise 
  1393.         
  1394.  
  1395.     
  1396.  
  1397.  
  1398. try:
  1399.     import atexit
  1400.     atexit.register(shutdown)
  1401. except ImportError:
  1402.     
  1403.     def exithook(status, old_exit = sys.exit):
  1404.         
  1405.         try:
  1406.             shutdown()
  1407.         finally:
  1408.             old_exit(status)
  1409.  
  1410.  
  1411.     sys.exit = exithook
  1412.  
  1413.